package com.zl.Exceptions;

import com.zl.common.Result;
import com.zl.util.Exceptions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;

@Slf4j
@RestControllerAdvice
public class ExceptionsHandler {

    @ExceptionHandler(value = Exception.class)
    public Result logicExceptionHandler(Exception e) {
        //如果是业务逻辑异常，返回具体的错误码与提示信息
        if (e instanceof RequestException) {
            return Result.error(e.getMessage());
        } else if (e instanceof AccessDeniedException) {
            log.error("权限不足：{}", e.getMessage());
            return Result.error(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
        } else {
            //对系统级异常进行日志记录
            log.error("系统异常：{}", Exceptions.getStackTraceAsString(e));
            return Result.error("系统异常");
        }
    }
}
